﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using COM.Web;
using COM.Service;
using SampleApp.Service;
using SampleApp.Web.Default.Models;
using SampleApp.Web.Service;

namespace SampleApp.Web.Default.Controllers
{
    public class AccountController : Controller
    {
        private IAppLoginService loginService = Unity.Instance.GetService<IAppLoginService>();
        private ISysUserService appUserService = Unity.Instance.GetService<ISysUserService>();
        private IWebPermissionService permissionService = Unity.Instance.GetService<IWebPermissionService>();

        // GET: /Account/LogOn
        public ActionResult LogOn()
        {
            return View();
        }

        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //Todo:管理人员暂时用此入口登录
                if (model.UserCode.ToUpper() == "Admin".ToUpper())
                {
                    if (loginService.LoginAsAdministrator(model.UserCode, model.Password))
                    {
                        var rememberMeCookie = new System.Web.HttpCookie("RememberMe", model.RememberMe.ToString());
                        System.Web.HttpContext.Current.Response.Cookies.Add(rememberMeCookie);

                        if (string.IsNullOrEmpty(returnUrl))
                            return Redirect("~/");
                        else
                            return Redirect(returnUrl);
                    }
                    else
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
                else //用户登录入口
                {
                    if (loginService.LoginAsSampleUser(model.UserCode, model.Password))
                    {
                        var rememberMeCookie = new System.Web.HttpCookie("RememberMe", model.RememberMe.ToString());
                        System.Web.HttpContext.Current.Response.Cookies.Add(rememberMeCookie);

                        return Redirect("~/SysModule/Home/Index");

                        //if (string.IsNullOrEmpty(returnUrl))
                        //    return Redirect("~/");
                        //else
                        //    return Redirect(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            this.loginService.LogOut();
            return Redirect("~/");
        }


        public ActionResult UserInfo()
        {
            var employee = this.permissionService.CurrentUser.AsRole<SampleApp.Data.AppEmployee>();
            var user = this.permissionService.CurrentUser as PermissionUserPrincipal;
            ViewBag.DeptName = employee == null ? user.UserName : employee.DeptCode;
            return View();
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            //this.permissionService.AllowOperateOrLogin(EnumPermissionNameWeb.RegisterAnySampleWebUser);
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            //暂时仅管理员可创建项目登录账号
            //this.permissionService.AllowOperateOrLogin(EnumWebPermissionName.RegisterAnySampleWebUser);

            //if (ModelState.IsValid)
            //{
            //    List<string> systemUser = new List<string>()
            //    {"Admin","Test","Dev","Administrator","Sample","Client",
            //    "Employee","System","Sys","App","Application","User"
            //    };
            //    if(systemUser.ToList().Exists(i=>i.ToLower() == model.UserName.ToLower()))
            //        throw new ApplicationException(string.Format("此账号已存在!"));

            //    var app = this.sampleService.GetSampleByName(model.SampleName);
            //    this.appUserService.CreateSampleUser(model.Email, model.UserName, model.Email, model.Password,app.SampleID);
            //    return Redirect("~/");
            //}

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                bool changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
